package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LoginException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * Author ChenYongSheng
 * Date 2025/10/14 16:56
 */
public class JwtUtil {

    static long tokenExpiration =60*60*12*1000L;
//    static long tokenExpiration =60 *1000L;
    static SecretKey tokenSignKey = Keys.hmacShaKeyFor("124jiuh124uihiuy1u24o124oiu12o4u1io24u".getBytes());

    /**
     * 创建生成token令牌
     * @param userId 用户id
     * @param userName 用户姓名
     * @return 返回token令牌
     */
    public static String createToken(Long userId,String userName){

        return Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis()+ tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(tokenSignKey)
                .compact();

    }

    /**
     * 解析token令牌
     * @param token token令牌
     * @return 解析后的数据，放到SystemUser中即可使用
     */
    public static Claims parseToken(String token){
       try{
           Jws<Claims> claimsJws = Jwts.parserBuilder()
                   .setSigningKey(tokenSignKey)
                   .build()
                   .parseClaimsJws(token);

           return claimsJws.getBody();
       } catch (ExpiredJwtException e) {
           //token过期
           throw new LoginException(ResultCodeEnum.TOKEN_EXPIRED);
       }catch (JwtException e){
           throw  new LoginException(ResultCodeEnum.TOKEN_INVALID);
       }
    }
}
